package com.buaa.divinationmaster.interpretation;

import android.content.Context;
import android.content.res.Resources;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;  
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解读内容生活化引擎
 * 将专业占卜术语转化为贴近生活、易懂的表达
 * 
 * 核心功能：
 * - 专业术语到生活化语言的智能转换
 * - 上下文感知的动态解读生成
 * - 多层次解读结构（概述、详细、建议）
 * - 情感色彩和语气调节
 */
public class InterpretationEngine {
    
    private static final String TAG = "InterpretationEngine";
    
    /**
     * 解读风格枚举
     */
    public enum InterpretationStyle {
        FRIENDLY("友好亲切", "像朋友一样温和贴心"),
        PROFESSIONAL("专业权威", "保持专业但易懂"),
        ENCOURAGING("鼓励积极", "积极正面，给人信心"),
        REALISTIC("客观现实", "客观分析，直面现实"),
        MYSTICAL("神秘深邃", "保留神秘感但不晦涩");
        
        private final String name;
        private final String description;
        
        InterpretationStyle(String name, String description) {
            this.name = name;
            this.description = description;
        }
        
        public String getName() { return name; }
        public String getDescription() { return description; }
    }
    
    /**
     * 解读层级
     */
    public enum InterpretationLevel {
        OVERVIEW("总体概述", 1),
        DETAILED("详细分析", 2), 
        PRACTICAL("实用建议", 3),
        EMOTIONAL("情感指导", 4);
        
        private final String name;
        private final int priority;
        
        InterpretationLevel(String name, int priority) {
            this.name = name;
            this.priority = priority;
        }
        
        public String getName() { return name; }
        public int getPriority() { return priority; }
    }
    
    /**
     * 解读结果数据结构
     */
    public static class InterpretationResult {
        private String overview;           // 总体概述
        private String detailed;          // 详细分析  
        private String practical;         // 实用建议
        private String emotional;         // 情感指导
        private InterpretationStyle style; // 使用的风格
        private Map<String, String> metadata; // 元数据
        
        public InterpretationResult() {
            this.metadata = new HashMap<>();
        }
        
        // Getters and Setters
        public String getOverview() { return overview; }
        public void setOverview(String overview) { this.overview = overview; }
        
        public String getDetailed() { return detailed; }
        public void setDetailed(String detailed) { this.detailed = detailed; }
        
        public String getPractical() { return practical; }
        public void setPractical(String practical) { this.practical = practical; }
        
        public String getEmotional() { return emotional; }
        public void setEmotional(String emotional) { this.emotional = emotional; }
        
        public InterpretationStyle getStyle() { return style; }
        public void setStyle(InterpretationStyle style) { this.style = style; }
        
        public Map<String, String> getMetadata() { return metadata; }
        public void addMetadata(String key, String value) { this.metadata.put(key, value); }
        
        /**
         * 根据指定层级获取解读内容
         */
        public String getContentByLevel(InterpretationLevel level) {
            switch (level) {
                case OVERVIEW: return overview;
                case DETAILED: return detailed;
                case PRACTICAL: return practical;
                case EMOTIONAL: return emotional;
                default: return overview;
            }
        }
        
        /**
         * 获取完整的格式化解读
         */
        public String getFormattedInterpretation() {
            StringBuilder sb = new StringBuilder();
            
            if (overview != null && !overview.isEmpty()) {
                sb.append("【总体解读】\n").append(overview).append("\n\n");
            }
            
            if (detailed != null && !detailed.isEmpty()) {
                sb.append("【详细分析】\n").append(detailed).append("\n\n");
            }
            
            if (practical != null && !practical.isEmpty()) {
                sb.append("【实用建议】\n").append(practical).append("\n\n");
            }
            
            if (emotional != null && !emotional.isEmpty()) {
                sb.append("【情感指导】\n").append(emotional);
            }
            
            return sb.toString().trim();
        }
    }
    
    private Context context;
    private LifestyleInterpreter lifestyleInterpreter;
    private ContextAnalyzer contextAnalyzer;
    private Random random;
    
    // 专业术语到生活化表达的映射表
    private Map<String, List<String>> termTranslations;
    private Map<String, List<String>> emotionalModifiers;
    private Map<String, List<String>> practicalPhrases;
    
    public InterpretationEngine(Context context) {
        this.context = context;
        this.lifestyleInterpreter = new LifestyleInterpreter(context);
        this.contextAnalyzer = new ContextAnalyzer(context);
        this.random = new Random();
        
        initializeTranslationMaps();
    }
    
    /**
     * 核心解读方法 - 将原始解读转换为生活化表达
     */
    public InterpretationResult generateLifestyleInterpretation(
            String originalInterpretation, 
            String question,
            InterpretationStyle style) {
        
        InterpretationResult result = new InterpretationResult();
        result.setStyle(style);
        
        // 分析问题上下文
        ContextAnalyzer.QuestionContext questionContext = 
            contextAnalyzer.analyzeQuestion(question);
        
        // 解析原始解读结构
        Map<String, String> parsedContent = parseOriginalInterpretation(originalInterpretation);
        
        // 生成各层级的生活化解读
        result.setOverview(generateOverview(parsedContent, questionContext, style));
        result.setDetailed(generateDetailedAnalysis(parsedContent, questionContext, style));
        result.setPractical(generatePracticalAdvice(parsedContent, questionContext, style));
        result.setEmotional(generateEmotionalGuidance(parsedContent, questionContext, style));
        
        // 添加元数据
        result.addMetadata("question_category", questionContext.getCategory().getName());
        result.addMetadata("emotional_tone", questionContext.getEmotionalTone().getName());
        result.addMetadata("generation_time", String.valueOf(System.currentTimeMillis()));
        
        return result;
    }
    
    /**
     * 解析原始解读内容的结构
     */
    private Map<String, String> parseOriginalInterpretation(String originalInterpretation) {
        Map<String, String> parsed = new HashMap<>();
        
        // 使用正则表达式提取不同部分
        Pattern headerPattern = Pattern.compile("【([^】]+)】([^【]*)");
        Matcher matcher = headerPattern.matcher(originalInterpretation);
        
        while (matcher.find()) {
            String header = matcher.group(1).trim();
            String content = matcher.group(2).trim();
            parsed.put(header, content);
        }
        
        // 如果没有明确的结构，将整个内容作为基础内容
        if (parsed.isEmpty()) {
            parsed.put("基础解读", originalInterpretation);
        }
        
        return parsed;
    }
    
    /**
     * 生成总体概述
     */
    private String generateOverview(Map<String, String> parsedContent, 
                                  ContextAnalyzer.QuestionContext context,
                                  InterpretationStyle style) {
        
        StringBuilder overview = new StringBuilder();
        
        // 友好的开场
        String opening = getStyleAppropriateOpening(context, style);
        overview.append(opening);
        
        // 主要信息的生活化表达
        String mainContent = "";
        if (parsedContent.containsKey("基础解读")) {
            mainContent = parsedContent.get("基础解读");
        } else if (parsedContent.containsKey("总结建议")) {
            mainContent = parsedContent.get("总结建议");
        } else {
            // 取第一个可用的内容
            mainContent = parsedContent.values().iterator().next();
        }
        
        String lifestylizedContent = lifestyleInterpreter.convertToLifestyle(
            mainContent, context.getCategory(), style);
        overview.append(lifestylizedContent);
        
        return overview.toString();
    }
    
    /**
     * 生成详细分析
     */
    private String generateDetailedAnalysis(Map<String, String> parsedContent,
                                         ContextAnalyzer.QuestionContext context,
                                         InterpretationStyle style) {
        
        StringBuilder detailed = new StringBuilder();
        
        // 分析各个方面
        for (Map.Entry<String, String> entry : parsedContent.entrySet()) {
            String section = entry.getKey();
            String content = entry.getValue();
            
            if (section.equals("基础解读")) continue; // 已在概述中使用
            
            String lifestylizedSection = lifestyleInterpreter.convertSectionToLifestyle(
                section, content, context.getCategory(), style);
            
            if (!lifestylizedSection.isEmpty()) {
                detailed.append(lifestylizedSection).append("\n\n");
            }
        }
        
        return detailed.toString().trim();
    }
    
    /**
     * 生成实用建议
     */
    private String generatePracticalAdvice(Map<String, String> parsedContent,
                                         ContextAnalyzer.QuestionContext context,
                                         InterpretationStyle style) {
        
        List<String> advice = new ArrayList<>();
        
        // 基于问题类别生成相关建议
        switch (context.getCategory()) {
            case LOVE_RELATIONSHIP:
                advice.addAll(generateLoveAdvice(parsedContent, style));
                break;
            case CAREER_WORK:
                advice.addAll(generateCareerAdvice(parsedContent, style));
                break;
            case HEALTH_WELLBEING:
                advice.addAll(generateHealthAdvice(parsedContent, style));
                break;
            case MONEY_FINANCE:
                advice.addAll(generateFinanceAdvice(parsedContent, style));
                break;
            case PERSONAL_GROWTH:
                advice.addAll(generateGrowthAdvice(parsedContent, style));
                break;
            case GENERAL:
            default:
                advice.addAll(generateGeneralAdvice(parsedContent, style));
                break;
        }
        
        return formatAdviceList(advice, style);
    }
    
    /**
     * 生成情感指导
     */
    private String generateEmotionalGuidance(Map<String, String> parsedContent,
                                           ContextAnalyzer.QuestionContext context,
                                           InterpretationStyle style) {
        
        StringBuilder guidance = new StringBuilder();
        
        // 基于情感基调提供指导
        switch (context.getEmotionalTone()) {
            case ANXIOUS:
                guidance.append("我理解你现在可能有些担心和不安。");
                break;
            case HOPEFUL:
                guidance.append("你的积极态度很好，这会帮助你更好地应对挑战。");
                break;
            case CONFUSED:
                guidance.append("困惑是很正常的，让我们一起理清思路。");
                break;
            case DETERMINED:
                guidance.append("你的决心很值得赞赏，保持这份坚定很重要。");
                break;
            case NEUTRAL:
            default:
                guidance.append("从占卜的角度来看，");
                break;
        }
        
        // 添加情感支持和鼓励
        String emotionalSupport = generateEmotionalSupport(parsedContent, context, style);
        guidance.append(emotionalSupport);
        
        return guidance.toString();
    }
    
    /**
     * 根据风格获取合适的开场白
     */
    private String getStyleAppropriateOpening(ContextAnalyzer.QuestionContext context, 
                                            InterpretationStyle style) {
        List<String> openings = new ArrayList<>();
        
        switch (style) {
            case FRIENDLY:
                openings.addAll(Arrays.asList(
                    "从占卜的角度来看，",
                    "根据卡牌的指引，",
                    "让我为你解读一下，"
                ));
                break;
            case PROFESSIONAL:
                openings.addAll(Arrays.asList(
                    "综合分析显示，",
                    "根据占卜结果，",
                    "从专业角度解读，"
                ));
                break;
            case ENCOURAGING:
                openings.addAll(Arrays.asList(
                    "好消息是，",
                    "值得高兴的是，",
                    "从积极的角度看，"
                ));
                break;
            case REALISTIC:
                openings.addAll(Arrays.asList(
                    "客观来说，",
                    "实际情况是，",
                    "根据当前的情况，"
                ));
                break;
            case MYSTICAL:
                openings.addAll(Arrays.asList(
                    "宇宙的能量告诉我们，",
                    "从神秘学的角度，",
                    "灵性的指引显示，"
                ));
                break;
        }
        
        return openings.get(random.nextInt(openings.size()));
    }
    
    /**
     * 初始化翻译映射表
     */
    private void initializeTranslationMaps() {
        termTranslations = new HashMap<>();
        emotionalModifiers = new HashMap<>();
        practicalPhrases = new HashMap<>();
        
        // 专业术语翻译
        termTranslations.put("阴性能量", Arrays.asList("内向的力量", "安静的能量", "沉稳的特质"));
        termTranslations.put("阳性能量", Arrays.asList("外向的力量", "积极的能量", "活跃的特质"));
        termTranslations.put("逆位", Arrays.asList("相反的含义", "需要注意的方面", "阻碍或挑战"));
        termTranslations.put("正位", Arrays.asList("正面的含义", "顺利的发展", "积极的能量"));
        
        // 情感修饰词
        emotionalModifiers.put("positive", Arrays.asList("很好", "不错", "令人欣慰", "值得高兴"));
        emotionalModifiers.put("negative", Arrays.asList("需要注意", "要小心", "可能会有挑战", "需要谨慎"));
        emotionalModifiers.put("neutral", Arrays.asList("比较平稳", "相对稳定", "没有太大波动"));
        
        // 实用建议短语
        practicalPhrases.put("action", Arrays.asList("建议你", "可以考虑", "不妨试试", "或许应该"));
        practicalPhrases.put("caution", Arrays.asList("要注意", "需要小心", "要谨慎", "要提防"));
        practicalPhrases.put("opportunity", Arrays.asList("这是个好机会", "值得把握", "可以抓住", "不要错过"));
    }
    
    // 生成各类建议的辅助方法
    private List<String> generateLoveAdvice(Map<String, String> content, InterpretationStyle style) {
        List<String> advice = new ArrayList<>();
        advice.add("在感情方面，保持真诚的沟通很重要。");
        advice.add("给对方一些空间，同时也要表达自己的感受。");
        advice.add("不要急于求成，让感情自然发展。");
        return advice;
    }
    
    private List<String> generateCareerAdvice(Map<String, String> content, InterpretationStyle style) {
        List<String> advice = new ArrayList<>();
        advice.add("在工作上，保持专业态度会为你加分。");
        advice.add("多学习新技能，提升自己的竞争力。");
        advice.add("与同事保持良好关系，建立人脉网络。");
        return advice;
    }
    
    private List<String> generateHealthAdvice(Map<String, String> content, InterpretationStyle style) {
        List<String> advice = new ArrayList<>();
        advice.add("注意身体健康，保持规律的作息。");
        advice.add("适当运动，保持身心平衡。");
        advice.add("如有不适，及时就医检查。");
        return advice;
    }
    
    private List<String> generateFinanceAdvice(Map<String, String> content, InterpretationStyle style) {
        List<String> advice = new ArrayList<>();
        advice.add("理财要谨慎，不要冒不必要的风险。");
        advice.add("制定预算计划，控制不必要的开支。");
        advice.add("可以考虑多元化投资，分散风险。");
        return advice;
    }
    
    private List<String> generateGrowthAdvice(Map<String, String> content, InterpretationStyle style) {
        List<String> advice = new ArrayList<>();
        advice.add("保持学习的心态，不断提升自己。");
        advice.add("勇于面对挑战，从中获得成长。");
        advice.add("定期反思，总结经验教训。");
        return advice;
    }
    
    private List<String> generateGeneralAdvice(Map<String, String> content, InterpretationStyle style) {
        List<String> advice = new ArrayList<>();
        advice.add("保持积极的心态，相信事情会朝好的方向发展。");
        advice.add("耐心等待时机，不要急于求成。"); 
        advice.add("相信自己的直觉，同时也要理性分析。");
        return advice;
    }
    
    private String formatAdviceList(List<String> advice, InterpretationStyle style) {
        if (advice.isEmpty()) return "";
        
        StringBuilder formatted = new StringBuilder();
        for (int i = 0; i < advice.size(); i++) {
            formatted.append(String.format("%d. %s", i + 1, advice.get(i)));
            if (i < advice.size() - 1) {
                formatted.append("\n");
            }
        }
        return formatted.toString();
    }
    
    private String generateEmotionalSupport(Map<String, String> content,
                                          ContextAnalyzer.QuestionContext context,
                                          InterpretationStyle style) {
        return "记住，占卜只是一个参考，最重要的是要相信自己的能力，积极面对生活中的各种挑战。";
    }
}
